import { type FC, useRef } from 'react';
import { useMemoizedFn } from 'ahooks';
import Carousel from 'react-native-reanimated-carousel';
import type { ICarouselInstance } from 'react-native-reanimated-carousel';
import { sliderStyles, PAGE_HEIGHT } from './styles';
import type { SliderProps } from './types';
import SliderItem from './item';

const Slider: FC<SliderProps> = (props) => {
  const { items = [], onChange } = props;
  const r = useRef<ICarouselInstance>(null);

  const scrollTo = useMemoizedFn((count: number) => {
    r.current?.scrollTo({ animated: true, count });
  });

  return (
    <Carousel
      ref={r}
      vertical
      data={items}
      loop={false}
      pagingEnabled
      defaultIndex={2}
      height={PAGE_HEIGHT}
      onSnapToItem={onChange}
      style={sliderStyles.container}
      renderItem={({ item, animationValue: val }) => (
        <SliderItem
          label={item.label}
          animationValue={val}
          onPress={() => scrollTo(val.value)}
        />
      )}
    />
  );
}

export default Slider;